package com.example.light.web.meeting.controller;

import com.example.light.common.exception.GlobalException;
import com.example.light.common.result.CodeMsg;
import com.example.light.common.result.Result;
import com.example.light.redis.MeetKey;
import com.example.light.redis.RedisService;
import com.example.light.web.meeting.entity.OaMeetRecord;
import com.example.light.web.meeting.service.MeetService;
import com.example.light.web.meeting.service.OaRoomService;
import com.example.light.web.meeting.vo.MeetListVO;
import com.example.light.web.meeting.vo.MeetRecordVO;
import com.example.light.web.system.entity.User;
import com.example.light.web.system.service.UserService;
import com.github.pagehelper.PageInfo;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: lizhilong
 * @Description:
 * @Date: Created in 21:05 2018/8/27
 * @Modified By:
 */
@Controller
public class MeetController {
    @Autowired
    private MeetService meetService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private OaRoomService roomService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "meetList", method = RequestMethod.POST)
    @ResponseBody
    public MeetListVO<List<OaMeetRecord>> listMeetRecord(Integer pageNumber, Integer pageSize, String searchInfo) {
        if (pageNumber == null || pageSize == null) {
            throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_PAGEINFO);
        }
        if (searchInfo != null) {
            PageInfo meetRecordList = meetService.listMeetRecord(pageNumber, pageSize,searchInfo);
            if (meetRecordList.getList().isEmpty()) return new MeetListVO<>(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
            return new MeetListVO<List<OaMeetRecord>>(meetRecordList.getList(), meetRecordList.getTotal());
        }
        PageInfo meetRecordList = meetService.listMeetRecord(pageNumber, pageSize);
        if (meetRecordList.getList().isEmpty()) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        return new MeetListVO<List<OaMeetRecord>>(meetRecordList.getList(), meetRecordList.getTotal());
    }

    /**
     * @param meetRecord 会议记录, meetTime 会议时间, user 组织者, attendeeIds 参会人员ID
     * @return com.example.light.common.result.Result
     * @author lizhilong
     * @date 2018/8/29 14:58
     * @description: 会议添加功能
     */
    @RequestMapping(value = "addMeetRecord", method = RequestMethod.POST)
    @ResponseBody
    public Result addMeetRecord(OaMeetRecord meetRecord, String meetTime, User user, Integer[] attendeeIds) {
        DateTime time = DateTime.parse(meetTime, DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss"));
        meetRecord.setOrganizerId(user.getUserId());
        if ( meetRecord == null) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        meetRecord.setMeetStart(time.toDate());
        meetService.addMeetRecord(meetRecord, attendeeIds);
        return new Result().success();
    }
    //---------------  跳转到会议列表界面 ---------------
    @RequestMapping("toMeetList")
    public String meetListView(){
        redisService.delete(new MeetKey("MeetRecordVO"), "meetRecord");
        return "meeting/meetlist";
    }
    //---------------  条转到添加会议界面  ---------------
    @RequestMapping("toAddMeet")
    public String addMeetView(Model model) {
        roomService.roomList(model);
        userService.getUserList(model);
        return "meeting/add_meet";
    }

    //---------------  条转到修改会议界面  ---------------
    @RequestMapping("toModifyMeet")
    public String modifyMeetView(@RequestParam("meetId") Integer meetId, Model model,HttpServletResponse response) {
        if (meetId == null) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        MeetRecordVO meetRecordVO = meetService.getMeetByMeetId(meetId);
        if (meetRecordVO == null) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        User organizer = userService.getUserByUserId(meetRecordVO.getOrganizerId());
        model.addAttribute("meetRecord", meetRecordVO);
        model.addAttribute("organizer",organizer);
        int length = meetRecordVO.getMeetAttendees().size();
        Integer[] ids = new Integer[length];
        for (int i = 0; i < length; i++) {
            ids[i] = meetRecordVO.getMeetAttendees().get(i).getUserId();
        }
        meetService.addCookie(response,meetRecordVO);
        roomService.roomList(model);
        userService.getNotExistsUser(model,ids);
        return "meeting/modify_meet";
    }
    //---------------  条转到会议详情界面  ---------------
    @RequestMapping("toMeetDetails")
    public String detailsMeetView(@RequestParam("meetId")Integer meetId, Model model, HttpServletResponse response){
        if (meetId == null) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        MeetRecordVO meetRecordVO = meetService.getMeetByMeetId(meetId);
        if (meetRecordVO == null) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        User organizer = userService.getUserByUserId(meetRecordVO.getOrganizerId());
        model.addAttribute("meetRecord", meetRecordVO);
        model.addAttribute("organizer",organizer);
        meetService.addCookie(response,meetRecordVO);
        return "meeting/detailed_meet";
    }


    @RequestMapping(value = "modifyMeet", method = RequestMethod.POST)
    @ResponseBody
    public Result modifyMeet(MeetRecordVO meetRecordVO, String meetTime) {
        Date utilDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
        try {
            utilDate = sdf.parse(meetTime);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new GlobalException(CodeMsg.MeetingCodeMsg.MEETRECORD_EXCEPTION);
        }
        Date time = new java.sql.Date(utilDate.getTime());
        meetRecordVO.setMeetStart(time);
        meetService.updateMeetRecord(meetRecordVO);
        return new Result().success();
    }

    @RequestMapping(value = "deleteMeet", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteMeet(Integer[] meetIds){
        if(meetIds.length == 0) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        meetService.deleteMeetRecord(meetIds);
        return new Result().success();
    }

    @RequestMapping(value = "addMeetSummary",method = RequestMethod.POST)
    @ResponseBody
    public Result addMeetSummary(String meetSummary){
        if (meetSummary == null) return new Result().error(CodeMsg.MeetingCodeMsg.NO_MEETSUMMARY);
        meetService.addMeetSummary(meetSummary);
        return new Result().success();
    }
    /**
    *@description: 富文本编辑框，附件上传
    */
    @RequestMapping("attachmentUpload")
    @ResponseBody
    public Result attachmentUpload(@RequestParam(value = "attachment", required = false) MultipartFile attachment, User user){
        String userPhone = user.getUserPhone();
        if(userPhone == null) throw new GlobalException(CodeMsg.PersonalCodeMsg.NULL_PHONE);
        if(attachment == null) throw new GlobalException(CodeMsg.MeetingCodeMsg.NULL_ATTACHMENT);
        String dbPath = meetService.uploadFile(attachment, userPhone);
        return new Result().success(dbPath);
    }

    @RequestMapping("delAttends")
    @ResponseBody
    public Result deleteAttends(Integer id){
       meetService.deleteAttends(id);
       return Result.success();
    }

    @RequestMapping("searchMeetList")
    @ResponseBody
    public MeetListVO<List<OaMeetRecord>> searchInfo(Integer pageNumber, Integer pageSize, String searchInfo){
        if (pageNumber == null || pageSize == null) {
            throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_PAGEINFO);
        }
        if (searchInfo == null) {
            throw new GlobalException(CodeMsg.MeetingCodeMsg.NULL_SEARCHINFO);
        }
        PageInfo meetRecordList = meetService.listMeetRecord(pageNumber, pageSize);
        if (meetRecordList.getList().isEmpty()) throw new GlobalException(CodeMsg.MeetingCodeMsg.NO_MEETRECORD);
        return new MeetListVO<List<OaMeetRecord>>(meetRecordList.getList(), meetRecordList.getTotal());
    }
}
